import { ITreeConfig, TreeNode } from './module/tree.module';
import { TreeService } from './service/tree.service';
import { Component, Input, OnChanges, OnInit, ViewEncapsulation } from '@angular/core';
@Component({
    selector: 'wit-tree',
    templateUrl: 'tree.component.html',
    providers: [TreeService],
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./tree.component.scss']
})

export class TreeCompoent implements OnChanges, OnInit {
    @Input() treeConfig: ITreeConfig;
    data: Array<any>;
    menulist: Array<any>;
    selectType: string;
    selectedFile:any;
    selection:any;
    constructor() {
    }
    ngOnInit() {
        this.menulist = [{
            label: 'View',
            command: function () {
                console.log('View handle')
            }
        }, {
            label: 'Unselected',
            command: function () {
                console.log('unselected handle');
            }
        }];
    }

    ngOnChanges() {
        if (this.treeConfig && this.treeConfig.data) {
            this.data = this.treeConfig.data;
        }
        if (this.treeConfig && this.treeConfig.isRightMenu) {
            this.menulist = this.treeConfig.rightKeyMenu
        }
        if (this.treeConfig && this.treeConfig.selectType) {
            switch (this.treeConfig.selectType) {
                case 0:
                    this.selectType = 'single'
                    break;
                case 1:
                    this.selectType = 'multiple'
                    break;
                case 2:
                    this.selectType = 'checkbox'
                    break;
                default:
                    this.selectType = 'single'
                    break;
            }
        }else{
            this.selectType = 'single'
        }
    }
    nodeSelect(event) {
        if(this.treeConfig&&this.treeConfig.isOnSelected){
            this.treeConfig.onSelected(event,this.selection);
        }
    }
    
    nodeUnselect(event) {
        if(this.treeConfig&&this.treeConfig.isOnNodeUnselect){
            this.treeConfig.onNodeUnselect(event);
        }
    }
    expandToNode(event){
        if(this.treeConfig&&this.treeConfig.isOnNodeExpand){
            this.treeConfig.onNodeExpand(event);
        }
    }
    collapseToNode(event){
        if(this.treeConfig&&this.treeConfig.isOnNodeCollpase){
            this.treeConfig.onNodeCollpase(event);
        }
    }
    expandAll(){
        this.data.forEach( node => {
            this.expandRecursive(node, true);
        } );
    }

    collapseAll(){
        this.data.forEach( node => {
            this.expandRecursive(node, false);
        } );
    }

    private expandRecursive(node:TreeNode, isExpand:boolean){
        node.expanded = isExpand;
        if(node.children){
            node.children.forEach( childNode => {
                this.expandRecursive(childNode, isExpand);
            } );
        }
    }

}